package com.wjy.icu.common.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 文件处理
 * @author: wangjunyong
 * @date: 2021/6/10 13:18
 */
public class FileUtil {

    public static File strToFile(byte[] b, String path)  {
        File file = new File(path);
        FileOutputStream fis = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileOutputStream(file);
            bos = new BufferedOutputStream(fis);
            bos.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return file;
    }

    /**
     * 创建文件夹
     * @param path
     */
    public static void mkDir(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
    }
    /*   *//**创建文件*//*
    public static File createExcelFile(String name){
        File file=null;
        try {
            file=new File(name);
            if(!file.exists()){
                ExcelUtil.createExcel(file);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return file;
    }*/


    //文件上传
    public static String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String Directory = "Excel/";
        String fileName = file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath(Directory);
        File tempFile = new File(path, System.currentTimeMillis() + String.valueOf(fileName));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return path + tempFile.getName();
    }

    /**
     * 保存文件，直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = FileUtil.getFileName(multipartFile.getOriginalFilename());
//        String fileName = UUID.randomUUID().toString().replace("-", "") + ".png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }
    public static String saveImgInputStream(FileInputStream fileInputStream, MultipartFile multipartFile, String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = FileUtil.getFileName(multipartFile.getOriginalFilename());
//        String fileName = UUID.randomUUID().toString().replace("-", "") + ".png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName){
        return UUID.randomUUID().toString().replace("-", "") + FileUtil.getSuffix(fileOriginName);
    }


    public static String uploadFileNew(MultipartFile multipartFile, String location) throws Exception {
        //获取路径
        //事件  年月日
        Date date = new Date();
        String path=new SimpleDateFormat("yyyy/MM/dd/").format(date);
        String filePath = location+path;
        String file_name = null;
        try {
            file_name = FileUtil.saveImg(multipartFile, filePath);

            return "upload/v1/"+path+file_name;
        } catch (IOException e) {
            throw new Exception("上传失败");
        }
    }
    public static String uploadFileInputStream(FileInputStream inputStream, MultipartFile multipartFile, String location) throws Exception {
        //获取路径
        //事件  年月日
        Date date = new Date();
        String path=new SimpleDateFormat("yyyy/MM/dd/").format(date);
        String filePath = location+path;
        String file_name = null;
        try {
            file_name = FileUtil.saveImgInputStream(inputStream,multipartFile, filePath);

            return "upload/v1/"+path+file_name;
        } catch (IOException e) {
            throw new Exception("上传失败");
        }
    }

    public static String uploadFileNew(MultipartFile file, HttpServletRequest request) throws IOException {
        String Directory = "Excel/";
        String fileName = file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath(Directory);
        File tempFile = new File(path, System.currentTimeMillis() + String.valueOf(fileName));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return path + tempFile.getName();
    }
    public static List<String> uploadFilesNew(List<MultipartFile> multipartFiles, String location) throws Exception {
        List<String> uploads = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile.isEmpty() || StringUtils.isEmpty(multipartFile.getOriginalFilename())) {
                throw new Exception("上传失败");
            }
            String contentType = multipartFile.getContentType();
            if (!contentType.contains("")) {
                throw new Exception("上传失败");
            }
            //获取路径
            //事件  年月日
            Date date = new Date();
            String path = new SimpleDateFormat("yyyy/MM/dd/").format(date);
            String filePath = location + path;

            String file_name = null;
            try {
                file_name = FileUtil.saveImg(multipartFile, filePath);
                uploads.add("upload/v1/"+path+file_name);
            } catch (IOException e) {
                throw new Exception("上传失败");
            }
        }
        return uploads;
    }
}
